package com.maysev.myjob_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maysev.myjob_backend.common.R;
import com.maysev.myjob_backend.entity.Category;
import com.maysev.myjob_backend.entity.Subcategory;
import com.maysev.myjob_backend.service.CategoryService;
import com.maysev.myjob_backend.service.SubcategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 五七
 * @create 2023-04-03 15:41
 * @description:
 */
@RestController
@Slf4j
@RequestMapping("/categories")
@CrossOrigin("http://localhost:8082")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SubcategoryService subcategoryService;

    /**
     * 查询所有父级目录
     * @return
     */
    @GetMapping
    private R<List<Category>> getAllCategories(){
        List<Category> list = categoryService.list();
        return R.success(list);
    }

    /**
     * 根据catecategoryId查询所有子目录
     *  @param categoryId
     * @return
     */
    @GetMapping("/{categoryId}/subcategories")
    private R<List<Subcategory>> getSubcategoriesByCategoryId(@PathVariable Long categoryId){
        LambdaQueryWrapper<Subcategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subcategory::getCategoryId,categoryId);
        List<Subcategory> list = subcategoryService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 添加父级目录
     * @param category
     * @return
     */
    @PostMapping
    private R<String> createCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 添加子级目录
     * @param subcategory
     * @return
     */
    @PostMapping("/subcategories")
    private R<String> createSubcategory(@RequestBody Subcategory subcategory){
        subcategoryService.save(subcategory);
        return R.success("添加成功");
    }

    /**
     * 根据id查询子级目录名称
     * @param id
     * @return
     */
    @GetMapping("/subcategory/{id}")
    private R<String> getSubcategoryName(@PathVariable Long id){
        Subcategory subcategory = subcategoryService.getById(id);
        String name = subcategory.getName();
        return R.success(name);
    }
}
